package de.infotheo;

import java.math.BigInteger;

/**
 * The class OrderOfGroupMember contains a method to calculate the order of a group element
 * 
 * @author Eugen
 * 
 */
public class OrderOfGroupMember {

	/**
	 * The method calcOrderOfGroupMember calculates the order of a group
	 * element
	 * 
	 * @param g
	 *            element to get calculated the order of
	 * @param z
	 *            order of the group
	 * 
	 * @return order of the group element
	 */
	public BigInteger calcOrderOfGroupMember(BigInteger g, BigInteger z) {
		// start parameter to compare the bigintegers
		BigInteger x = new BigInteger("1");
		BigInteger y = new BigInteger("0");
		// iteration parameter
		int c;

		// powering the element modulo group order from 1 to group order and
		// stopping if the result is 1
		do {
			y = g.modPow(x, z);
			x = x.add(new BigInteger("1"));

			if (x.compareTo(z) == 1) {
				break;
			}
			c = y.compareTo(new BigInteger("1"));
		} while (c != 0);

		// correcting parameter x which is now bigger then z
		x = x.subtract(new BigInteger("1"));

		// verification parameter
		BigInteger verRes = g.modPow(x, z);

		// verification of the result 
		if (verRes.compareTo(new BigInteger("1")) == 0) {
			System.out.println("The order of " + g.toString() + " in Z_" + z
					+ " is: " + x.toString());

			// result = element order
			return x;
		} else {
			System.out.println("The order of " + g.toString() + " in Z_" + z
					+ " is: infinite!!! ");

			// order of the group is infinite
			return new BigInteger("0");
		}
	}
}
